from flask import Blueprint, request
from flask_restful import Api, Resource

from models.model import Worker, db
from utils.my_route import route_code, commit_route

worker_bp = Blueprint('worker_bp', __name__)
api = Api(worker_bp)


class WorkerView(Resource):
    def get(self, w_id=None):
        sql = db.session.query(Worker)
        if w_id:
            return route_code(sql.filter_by(id=w_id).one().to_dict())

        page = request.args.get("page", 1)
        per_page = request.args.get("per_page", 3)
        name = request.args.get("name", None)
        username = request.args.get("username", None)
        if name:
            sql = sql.filter(Worker.name.like(f"%{name}%"))
        if username:
            sql = sql.filter(Worker.username.like(f"%{username}%"))

        query = sql.paginate(page, per_page, error_out=False)
        return route_code({
            "workers": [i.to_dict() for i in query.items],
            "pages": query.pages,
        })

    def post(self):
        data = request.form
        db.session.add(Worker(**data))
        return commit_route("添加成功")

    def put(self, w_id=0):
        data = request.form
        Worker.query.filter(Worker.id == w_id).update(data)
        return commit_route("修改成功")

    def delete(self, w_id=0):
        Worker.query.filter(Worker.id == w_id).delete()
        return commit_route("删除成功")


api.add_resource(WorkerView, '/v2/staff/<int:w_id>', '/v2/staff')
